@camox/api 0.2.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +110 -0
- package/README.md +21 -0
- package/package.json +54 -0
- package/src/authorization.ts +110 -0
- package/src/db.ts +45 -0
- package/src/durable-objects/ai-job-scheduler.ts +135 -0
- package/src/durable-objects/project-room.ts +16 -0
- package/src/index.ts +125 -0
- package/src/lib/broadcast-invalidation.ts +17 -0
- package/src/lib/content-markdown.ts +117 -0
- package/src/lib/cross-domain.ts +186 -0
- package/src/lib/lexical-state.ts +196 -0
- package/src/lib/query-keys.ts +36 -0
- package/src/lib/resolve-environment.ts +218 -0
- package/src/lib/schedule-ai-job.ts +21 -0
- package/src/lib/slug.ts +42 -0
- package/src/middleware.ts +10 -0
- package/src/orpc.ts +65 -0
- package/src/router.ts +19 -0
- package/src/routes/auth.ts +110 -0
- package/src/routes/block-definitions.ts +216 -0
- package/src/routes/blocks.ts +800 -0
- package/src/routes/files.ts +463 -0
- package/src/routes/layouts.ts +164 -0
- package/src/routes/pages.ts +818 -0
- package/src/routes/projects.ts +267 -0
- package/src/routes/repeatable-items.ts +463 -0
- package/src/schema.ts +310 -0
- package/src/types.ts +29 -0
- package/src/worker.ts +3 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, MIT Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-MIT
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 Rémi de Juvigny
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the MIT license that is effective on the second anniversary of the date we make
|
|
91
|
+
the Software available. On or after that date, you may use the Software under
|
|
92
|
+
the MIT license, in which case the following will apply:
|
|
93
|
+
|
|
94
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
95
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
96
|
+
the Software without restriction, including without limitation the rights to
|
|
97
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
98
|
+
of the Software, and to permit persons to whom the Software is furnished to do
|
|
99
|
+
so, subject to the following conditions:
|
|
100
|
+
|
|
101
|
+
The above copyright notice and this permission notice shall be included in all
|
|
102
|
+
copies or substantial portions of the Software.
|
|
103
|
+
|
|
104
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
105
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
106
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
107
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
108
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
109
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
110
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
```txt
|
|
2
|
+
npm install
|
|
3
|
+
npm run dev
|
|
4
|
+
```
|
|
5
|
+
|
|
6
|
+
```txt
|
|
7
|
+
npm run deploy
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
[For generating/synchronizing types based on your Worker configuration run](https://developers.cloudflare.com/workers/wrangler/commands/#types):
|
|
11
|
+
|
|
12
|
+
```txt
|
|
13
|
+
npm run cf-typegen
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Pass the `CloudflareBindings` as generics when instantiation `Hono`:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
// src/index.ts
|
|
20
|
+
const app = new Hono<{ Bindings: CloudflareBindings }>();
|
|
21
|
+
```
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@camox/api",
|
|
3
|
+
"version": "0.2.0-alpha.5",
|
|
4
|
+
"files": [
|
|
5
|
+
"src"
|
|
6
|
+
],
|
|
7
|
+
"type": "module",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.ts",
|
|
11
|
+
"default": "./src/index.ts"
|
|
12
|
+
},
|
|
13
|
+
"./query-keys": {
|
|
14
|
+
"types": "./src/lib/query-keys.ts",
|
|
15
|
+
"default": "./src/lib/query-keys.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@hono/zod-validator": "^0.7.6",
|
|
20
|
+
"@orpc/server": "^1.13.13",
|
|
21
|
+
"@tanstack/ai": "^0.8.1",
|
|
22
|
+
"@tanstack/ai-openrouter": "^0.6.6",
|
|
23
|
+
"better-auth": "^1.5.6",
|
|
24
|
+
"drizzle-orm": "^0.45.2",
|
|
25
|
+
"fractional-indexing": "^3.2.0",
|
|
26
|
+
"hono": "^4.12.9",
|
|
27
|
+
"hono-party": "^2.0.3",
|
|
28
|
+
"outdent": "^0.8.0",
|
|
29
|
+
"partyserver": "^0.4.1",
|
|
30
|
+
"unique-names-generator": "^4.7.1",
|
|
31
|
+
"zod": "^4.3.6"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@cloudflare/workers-types": "^4.20260317.1",
|
|
35
|
+
"@libsql/client": "^0.17.2",
|
|
36
|
+
"@types/node": "^22.15.0",
|
|
37
|
+
"drizzle-kit": "^0.31.10",
|
|
38
|
+
"oxlint": "^0.15.15",
|
|
39
|
+
"tsx": "^4.21.0",
|
|
40
|
+
"wrangler": "^4.4.0"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"dev": "wrangler dev",
|
|
44
|
+
"deploy": "wrangler deploy --minify",
|
|
45
|
+
"cf-typegen": "wrangler types --env-interface CloudflareBindings",
|
|
46
|
+
"db:generate": "drizzle-kit generate",
|
|
47
|
+
"db:migrate:local": "wrangler d1 migrations apply DB --local",
|
|
48
|
+
"db:migrate:remote": "wrangler d1 migrations apply DB --remote",
|
|
49
|
+
"db:studio": "drizzle-kit studio",
|
|
50
|
+
"seed": "tsx scripts/dev-seed.ts",
|
|
51
|
+
"lint": "oxlint",
|
|
52
|
+
"check": "tsgo --noEmit && oxlint --fix"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { ORPCError } from "@orpc/server";
|
|
2
|
+
import { and, eq, or } from "drizzle-orm";
|
|
3
|
+
|
|
4
|
+
import type { Database } from "./db";
|
|
5
|
+
import {
|
|
6
|
+
member,
|
|
7
|
+
organizationTable,
|
|
8
|
+
blocks,
|
|
9
|
+
files,
|
|
10
|
+
layouts,
|
|
11
|
+
pages,
|
|
12
|
+
projects,
|
|
13
|
+
repeatableItems,
|
|
14
|
+
} from "./schema";
|
|
15
|
+
|
|
16
|
+
// --- Membership Helpers ---
|
|
17
|
+
|
|
18
|
+
export async function assertOrgMembership(db: Database, userId: string, orgSlug: string) {
|
|
19
|
+
const result = await db
|
|
20
|
+
.select({ id: member.id })
|
|
21
|
+
.from(member)
|
|
22
|
+
.innerJoin(organizationTable, eq(organizationTable.id, member.organizationId))
|
|
23
|
+
.where(and(eq(organizationTable.slug, orgSlug), eq(member.userId, userId)))
|
|
24
|
+
.get();
|
|
25
|
+
if (!result) throw new ORPCError("FORBIDDEN");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Verify user is a member of the org that owns a project (by project ID). */
|
|
29
|
+
async function assertProjectMembership(db: Database, projectId: number, userId: string) {
|
|
30
|
+
const result = await db
|
|
31
|
+
.select({ id: member.id })
|
|
32
|
+
.from(projects)
|
|
33
|
+
.innerJoin(organizationTable, eq(organizationTable.slug, projects.organizationSlug))
|
|
34
|
+
.innerJoin(
|
|
35
|
+
member,
|
|
36
|
+
and(eq(member.organizationId, organizationTable.id), eq(member.userId, userId)),
|
|
37
|
+
)
|
|
38
|
+
.where(eq(projects.id, projectId))
|
|
39
|
+
.get();
|
|
40
|
+
if (!result) throw new ORPCError("FORBIDDEN");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// --- Authorization Helpers ---
|
|
44
|
+
|
|
45
|
+
export async function getAuthorizedProject(db: Database, projectId: number, userId: string) {
|
|
46
|
+
const project = await db.select().from(projects).where(eq(projects.id, projectId)).get();
|
|
47
|
+
if (!project) return null;
|
|
48
|
+
await assertProjectMembership(db, projectId, userId);
|
|
49
|
+
return project;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function getAuthorizedProjectBySlug(db: Database, slug: string, userId: string) {
|
|
53
|
+
const project = await db.select().from(projects).where(eq(projects.slug, slug)).get();
|
|
54
|
+
if (!project) return null;
|
|
55
|
+
await assertProjectMembership(db, project.id, userId);
|
|
56
|
+
return project;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function assertPageAccess(db: Database, pageId: number, userId: string) {
|
|
60
|
+
const result = await db
|
|
61
|
+
.select({ page: pages, projectId: projects.id })
|
|
62
|
+
.from(pages)
|
|
63
|
+
.innerJoin(projects, eq(projects.id, pages.projectId))
|
|
64
|
+
.where(eq(pages.id, pageId))
|
|
65
|
+
.get();
|
|
66
|
+
if (!result) return null;
|
|
67
|
+
await assertProjectMembership(db, result.projectId, userId);
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function assertBlockAccess(db: Database, blockId: number, userId: string) {
|
|
72
|
+
const result = await db
|
|
73
|
+
.select({ block: blocks, projectId: projects.id, pagePath: pages.fullPath })
|
|
74
|
+
.from(blocks)
|
|
75
|
+
.leftJoin(pages, eq(blocks.pageId, pages.id))
|
|
76
|
+
.leftJoin(layouts, eq(blocks.layoutId, layouts.id))
|
|
77
|
+
.innerJoin(projects, or(eq(projects.id, pages.projectId), eq(projects.id, layouts.projectId)))
|
|
78
|
+
.where(eq(blocks.id, blockId))
|
|
79
|
+
.get();
|
|
80
|
+
if (!result) return null;
|
|
81
|
+
await assertProjectMembership(db, result.projectId, userId);
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function assertRepeatableItemAccess(db: Database, itemId: number, userId: string) {
|
|
86
|
+
const result = await db
|
|
87
|
+
.select({ item: repeatableItems, projectId: projects.id, pagePath: pages.fullPath })
|
|
88
|
+
.from(repeatableItems)
|
|
89
|
+
.innerJoin(blocks, eq(repeatableItems.blockId, blocks.id))
|
|
90
|
+
.leftJoin(pages, eq(blocks.pageId, pages.id))
|
|
91
|
+
.leftJoin(layouts, eq(blocks.layoutId, layouts.id))
|
|
92
|
+
.innerJoin(projects, or(eq(projects.id, pages.projectId), eq(projects.id, layouts.projectId)))
|
|
93
|
+
.where(eq(repeatableItems.id, itemId))
|
|
94
|
+
.get();
|
|
95
|
+
if (!result) return null;
|
|
96
|
+
await assertProjectMembership(db, result.projectId, userId);
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function assertFileAccess(db: Database, fileId: number, userId: string) {
|
|
101
|
+
const result = await db
|
|
102
|
+
.select({ file: files })
|
|
103
|
+
.from(files)
|
|
104
|
+
.innerJoin(projects, eq(projects.id, files.projectId))
|
|
105
|
+
.where(eq(files.id, fileId))
|
|
106
|
+
.get();
|
|
107
|
+
if (!result) return null;
|
|
108
|
+
await assertProjectMembership(db, result.file.projectId!, userId);
|
|
109
|
+
return result;
|
|
110
|
+
}
|
package/src/db.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { drizzle } from "drizzle-orm/d1";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
aiJobs,
|
|
5
|
+
account,
|
|
6
|
+
invitation,
|
|
7
|
+
member,
|
|
8
|
+
organizationTable,
|
|
9
|
+
session,
|
|
10
|
+
user,
|
|
11
|
+
verification,
|
|
12
|
+
blockDefinitions,
|
|
13
|
+
blocks,
|
|
14
|
+
environments,
|
|
15
|
+
files,
|
|
16
|
+
layouts,
|
|
17
|
+
pages,
|
|
18
|
+
projects,
|
|
19
|
+
repeatableItems,
|
|
20
|
+
} from "./schema";
|
|
21
|
+
|
|
22
|
+
const schema = {
|
|
23
|
+
projects,
|
|
24
|
+
environments,
|
|
25
|
+
pages,
|
|
26
|
+
layouts,
|
|
27
|
+
blocks,
|
|
28
|
+
repeatableItems,
|
|
29
|
+
files,
|
|
30
|
+
aiJobs,
|
|
31
|
+
blockDefinitions,
|
|
32
|
+
user,
|
|
33
|
+
session,
|
|
34
|
+
account,
|
|
35
|
+
verification,
|
|
36
|
+
organization: organizationTable,
|
|
37
|
+
member,
|
|
38
|
+
invitation,
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export function createDb(d1: D1Database) {
|
|
42
|
+
return drizzle(d1, { schema });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type Database = ReturnType<typeof createDb>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { DurableObject } from "cloudflare:workers";
|
|
2
|
+
import { eq, or } from "drizzle-orm";
|
|
3
|
+
|
|
4
|
+
import { createDb } from "../db";
|
|
5
|
+
import { broadcastInvalidation } from "../lib/broadcast-invalidation";
|
|
6
|
+
import { queryKeys } from "../lib/query-keys";
|
|
7
|
+
import { executeBlockSummary } from "../routes/blocks";
|
|
8
|
+
import { executeFileMetadata } from "../routes/files";
|
|
9
|
+
import { executePageSeo } from "../routes/pages";
|
|
10
|
+
import { executeRepeatableItemSummary } from "../routes/repeatable-items";
|
|
11
|
+
import { blocks, files, layouts, pages, projects, repeatableItems } from "../schema";
|
|
12
|
+
import type { Bindings } from "../types";
|
|
13
|
+
|
|
14
|
+
type JobParams = {
|
|
15
|
+
entityTable: string;
|
|
16
|
+
entityId: number;
|
|
17
|
+
type: string;
|
|
18
|
+
delayMs: number;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export class AiJobScheduler extends DurableObject<Bindings> {
|
|
22
|
+
async fetch(request: Request): Promise<Response> {
|
|
23
|
+
const url = new URL(request.url);
|
|
24
|
+
|
|
25
|
+
if (request.method === "POST" && url.pathname === "/schedule") {
|
|
26
|
+
const params: JobParams = await request.json();
|
|
27
|
+
await this.ctx.storage.put("job", params);
|
|
28
|
+
await this.ctx.storage.setAlarm(Date.now() + params.delayMs);
|
|
29
|
+
return new Response(JSON.stringify({ scheduled: true }), {
|
|
30
|
+
status: 202,
|
|
31
|
+
headers: { "Content-Type": "application/json" },
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return new Response("Not found", { status: 404 });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async alarm(): Promise<void> {
|
|
39
|
+
const params = await this.ctx.storage.get<JobParams>("job");
|
|
40
|
+
if (!params) return;
|
|
41
|
+
|
|
42
|
+
await this.ctx.storage.delete("job");
|
|
43
|
+
|
|
44
|
+
const db = createDb(this.env.DB);
|
|
45
|
+
const apiKey = this.env.OPEN_ROUTER_API_KEY;
|
|
46
|
+
|
|
47
|
+
const { entityTable, entityId, type } = params;
|
|
48
|
+
|
|
49
|
+
if (entityTable === "blocks" && type === "summary") {
|
|
50
|
+
const seoStale = await executeBlockSummary(db, apiKey, entityId);
|
|
51
|
+
if (seoStale) {
|
|
52
|
+
// Cascade: schedule page SEO regeneration
|
|
53
|
+
const { scheduleAiJob } = await import("../lib/schedule-ai-job");
|
|
54
|
+
scheduleAiJob(this.env.AI_JOB_SCHEDULER, {
|
|
55
|
+
entityTable: "pages",
|
|
56
|
+
entityId: seoStale.pageId,
|
|
57
|
+
type: "seo",
|
|
58
|
+
delayMs: 15000,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Broadcast block summary update
|
|
63
|
+
const projectId = await this.getBlockProjectId(db, entityId);
|
|
64
|
+
if (projectId) {
|
|
65
|
+
broadcastInvalidation(this.env.ProjectRoom, projectId, [
|
|
66
|
+
queryKeys.pages.getByPathAll,
|
|
67
|
+
queryKeys.blocks.getUsageCounts,
|
|
68
|
+
]);
|
|
69
|
+
}
|
|
70
|
+
} else if (entityTable === "repeatableItems" && type === "summary") {
|
|
71
|
+
const cascade = await executeRepeatableItemSummary(db, apiKey, entityId);
|
|
72
|
+
if (cascade) {
|
|
73
|
+
// Cascade: schedule parent block summary regeneration
|
|
74
|
+
const { scheduleAiJob } = await import("../lib/schedule-ai-job");
|
|
75
|
+
scheduleAiJob(this.env.AI_JOB_SCHEDULER, {
|
|
76
|
+
entityTable: "blocks",
|
|
77
|
+
entityId: cascade.blockId,
|
|
78
|
+
type: "summary",
|
|
79
|
+
delayMs: 5000,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Broadcast repeatable item summary update
|
|
84
|
+
const item = await db
|
|
85
|
+
.select()
|
|
86
|
+
.from(repeatableItems)
|
|
87
|
+
.where(eq(repeatableItems.id, entityId))
|
|
88
|
+
.get();
|
|
89
|
+
if (item) {
|
|
90
|
+
const projectId = await this.getBlockProjectId(db, item.blockId);
|
|
91
|
+
if (projectId) {
|
|
92
|
+
broadcastInvalidation(this.env.ProjectRoom, projectId, [
|
|
93
|
+
queryKeys.pages.getByPathAll,
|
|
94
|
+
queryKeys.blocks.getUsageCounts,
|
|
95
|
+
]);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
} else if (entityTable === "files" && type === "fileMetadata") {
|
|
99
|
+
await executeFileMetadata(db, apiKey, entityId);
|
|
100
|
+
|
|
101
|
+
const file = await db.select().from(files).where(eq(files.id, entityId)).get();
|
|
102
|
+
if (file?.projectId) {
|
|
103
|
+
broadcastInvalidation(this.env.ProjectRoom, file.projectId, [
|
|
104
|
+
queryKeys.files.list,
|
|
105
|
+
queryKeys.files.get(entityId),
|
|
106
|
+
]);
|
|
107
|
+
}
|
|
108
|
+
} else if (entityTable === "pages" && type === "seo") {
|
|
109
|
+
await executePageSeo(db, apiKey, entityId);
|
|
110
|
+
|
|
111
|
+
const page = await db.select().from(pages).where(eq(pages.id, entityId)).get();
|
|
112
|
+
if (page) {
|
|
113
|
+
broadcastInvalidation(this.env.ProjectRoom, page.projectId, [
|
|
114
|
+
queryKeys.pages.list,
|
|
115
|
+
queryKeys.pages.getById(entityId),
|
|
116
|
+
]);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private async getBlockProjectId(
|
|
122
|
+
db: ReturnType<typeof createDb>,
|
|
123
|
+
blockId: number,
|
|
124
|
+
): Promise<number | null> {
|
|
125
|
+
const result = await db
|
|
126
|
+
.select({ projectId: projects.id })
|
|
127
|
+
.from(blocks)
|
|
128
|
+
.leftJoin(pages, eq(blocks.pageId, pages.id))
|
|
129
|
+
.leftJoin(layouts, eq(blocks.layoutId, layouts.id))
|
|
130
|
+
.innerJoin(projects, or(eq(projects.id, pages.projectId), eq(projects.id, layouts.projectId)))
|
|
131
|
+
.where(eq(blocks.id, blockId))
|
|
132
|
+
.get();
|
|
133
|
+
return result?.projectId ?? null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Server } from "partyserver";
|
|
2
|
+
|
|
3
|
+
import type { InvalidationMessage } from "../lib/query-keys";
|
|
4
|
+
import type { Bindings } from "../types";
|
|
5
|
+
|
|
6
|
+
export class ProjectRoom extends Server<Bindings> {
|
|
7
|
+
async onRequest(request: Request): Promise<Response> {
|
|
8
|
+
if (request.method !== "POST") {
|
|
9
|
+
return new Response("Method not allowed", { status: 405 });
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const message: InvalidationMessage = await request.json();
|
|
13
|
+
this.broadcast(JSON.stringify(message));
|
|
14
|
+
return new Response("OK", { status: 200 });
|
|
15
|
+
}
|
|
16
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { RPCHandler } from "@orpc/server/fetch";
|
|
2
|
+
import { Hono } from "hono";
|
|
3
|
+
import { partyserverMiddleware } from "hono-party";
|
|
4
|
+
import { cors } from "hono/cors";
|
|
5
|
+
|
|
6
|
+
import { createDb } from "./db";
|
|
7
|
+
import { router } from "./router";
|
|
8
|
+
import { authRoutes, createAuth } from "./routes/auth";
|
|
9
|
+
import { fileHonoRoutes } from "./routes/files";
|
|
10
|
+
import type { AppEnv } from "./types";
|
|
11
|
+
|
|
12
|
+
export type { Router } from "./router";
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// Hono app + global middleware
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
const app = new Hono<AppEnv>();
|
|
19
|
+
|
|
20
|
+
// Inject db into every request
|
|
21
|
+
app.use("*", async (c, next) => {
|
|
22
|
+
c.set("db", createDb(c.env.DB));
|
|
23
|
+
await next();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// CORS — accepts any origin (Camox sites run on arbitrary domains)
|
|
27
|
+
app.use(
|
|
28
|
+
"*",
|
|
29
|
+
cors({
|
|
30
|
+
origin: (origin) => origin,
|
|
31
|
+
allowHeaders: [
|
|
32
|
+
"Content-Type",
|
|
33
|
+
"Authorization",
|
|
34
|
+
"Better-Auth-Cookie",
|
|
35
|
+
"x-sync-secret",
|
|
36
|
+
"x-environment-name",
|
|
37
|
+
],
|
|
38
|
+
allowMethods: ["POST", "GET", "OPTIONS"],
|
|
39
|
+
exposeHeaders: ["Content-Length", "Set-Better-Auth-Cookie"],
|
|
40
|
+
maxAge: 600,
|
|
41
|
+
credentials: true,
|
|
42
|
+
}),
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
// Session middleware — populates c.var.user/session
|
|
46
|
+
app.use("*", async (c, next) => {
|
|
47
|
+
const auth = createAuth(c.var.db, c.env);
|
|
48
|
+
const session = await auth.api.getSession({ headers: c.req.raw.headers });
|
|
49
|
+
|
|
50
|
+
if (!session) {
|
|
51
|
+
c.set("user", null);
|
|
52
|
+
c.set("session", null);
|
|
53
|
+
await next();
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
c.set("user", session.user);
|
|
58
|
+
c.set("session", session.session);
|
|
59
|
+
await next();
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// Environment name middleware — reads x-environment-name header, defaults to "production"
|
|
63
|
+
app.use("*", async (c, next) => {
|
|
64
|
+
c.set("environmentName", c.req.header("x-environment-name") || "production");
|
|
65
|
+
await next();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// PartyServer — intercepts WebSocket upgrade requests for real-time invalidation
|
|
69
|
+
app.use(
|
|
70
|
+
"*",
|
|
71
|
+
partyserverMiddleware<AppEnv>({
|
|
72
|
+
options: {
|
|
73
|
+
onBeforeConnect: async (req, _lobby, c) => {
|
|
74
|
+
const db = createDb(c.env.DB);
|
|
75
|
+
const auth = createAuth(db, c.env);
|
|
76
|
+
const session = await auth.api.getSession({ headers: req.headers });
|
|
77
|
+
if (!session) return new Response("Unauthorized", { status: 401 });
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
}),
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
// Hono routes (auth, file upload/serve)
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
app.route("/api/auth", authRoutes);
|
|
88
|
+
app.route("/files", fileHonoRoutes);
|
|
89
|
+
|
|
90
|
+
// ---------------------------------------------------------------------------
|
|
91
|
+
// oRPC handler (all other API procedures)
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
const rpcHandler = new RPCHandler(router);
|
|
95
|
+
|
|
96
|
+
app.all("/rpc/*", async (c) => {
|
|
97
|
+
const { matched, response } = await rpcHandler.handle(c.req.raw, {
|
|
98
|
+
prefix: "/rpc",
|
|
99
|
+
context: {
|
|
100
|
+
db: c.var.db,
|
|
101
|
+
user: c.var.user,
|
|
102
|
+
session: c.var.session,
|
|
103
|
+
env: c.env,
|
|
104
|
+
headers: c.req.raw.headers,
|
|
105
|
+
environmentName: c.var.environmentName,
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
if (matched) {
|
|
110
|
+
return new Response(response.body, response);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return c.notFound();
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
// Error logging (development)
|
|
118
|
+
// ---------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
app.onError((err, c) => {
|
|
121
|
+
console.error(`[${c.req.method}] ${c.req.path} →`, err);
|
|
122
|
+
return c.json({ error: "Internal Server Error" }, 500);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
export default app;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { InvalidationMessage, QueryKey } from "./query-keys";
|
|
2
|
+
|
|
3
|
+
export function broadcastInvalidation(
|
|
4
|
+
projectRoomNamespace: DurableObjectNamespace,
|
|
5
|
+
projectId: number,
|
|
6
|
+
targets: QueryKey[],
|
|
7
|
+
) {
|
|
8
|
+
const id = projectRoomNamespace.idFromName(String(projectId));
|
|
9
|
+
const stub = projectRoomNamespace.get(id);
|
|
10
|
+
const message: InvalidationMessage = { type: "invalidate", targets };
|
|
11
|
+
// Fire-and-forget — don't block the mutation response
|
|
12
|
+
stub.fetch("http://do/broadcast", {
|
|
13
|
+
method: "POST",
|
|
14
|
+
headers: { "Content-Type": "application/json" },
|
|
15
|
+
body: JSON.stringify(message),
|
|
16
|
+
});
|
|
17
|
+
}
|